package com.jcli.novel_p;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.Properties;

/**
 * 3.0添加了删除按钮
 * 1.添加了清空文件的按钮
 * 2.搜索功能：
 * 在界面上添加一个文本框供用户输入要搜索的键。
 * 当用户输入关键字并按下搜索按钮时，应用程序将遍历键值对，找到匹配的键值对并将其显示在现有的表格中。(后续可以使用即时搜索)
 * 如果搜索关键字为空，则会恢复显示所有键值对。
 * 3.添加分页功能，每页表格只显示20个键值对，需要显示当前页数与总页数。
 */
public class WriteToPropertiesSwingUpdatedWithDeleteButton01 {
    private Properties properties;
    private int addedCount = 0;
    private JFrame frame;
    private DefaultTableModel tableModel;
    private JTable table;

    public WriteToPropertiesSwingUpdatedWithDeleteButton01() {
        properties = new Properties();

        try (InputStream inputStream = new FileInputStream("src/main/resources/config.properties")) {
            properties.load(new InputStreamReader(inputStream, "UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 创建Swing界面
        frame = new JFrame("配置属性编辑器");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 400);
        frame.setLayout(new BorderLayout());

        // 创建表格模型和表格
        tableModel = new DefaultTableModel();
        tableModel.addColumn("键");
        tableModel.addColumn("值");
        table = new JTable(tableModel);

        // 设置表格中的字体大小和粗体
        Font tableFont = new Font(Font.SANS_SERIF, Font.BOLD, 15);
        table.setFont(tableFont);

        // 设置表头的字体大小和粗体
        JTableHeader tableHeader = table.getTableHeader();
        Font headerFont = new Font(Font.SANS_SERIF, Font.BOLD, 15);
        tableHeader.setFont(headerFont);

        // 创建表格模型和表格
        tableModel = new DefaultTableModel();
        tableModel.addColumn("键");
        tableModel.addColumn("值");
        tableModel.addColumn("操作");
        table = new JTable(tableModel);

        // 创建属性删除按钮列渲染器和编辑器
        table.getColumnModel().getColumn(2).setCellRenderer(new ButtonRenderer());
        table.getColumnModel().getColumn(2).setCellEditor(new ButtonEditor(new JCheckBox()));

        // 将属性加载到表格模型中
        loadPropertiesToTableModel();

        // 创建文本框和按钮
        JTextField keyTextField = new JTextField(20);
        JTextField valueTextField = new JTextField(20);
        JButton addButton = new JButton("添加属性");
        JButton exitButton = new JButton("退出");
        JButton clearButton = new JButton("清空所有属性");// 创建按钮

        // 创建文本框和搜索按钮
        JTextField searchField = new JTextField(20);
        JButton searchButton = new JButton("搜索");

        // 添加文本框和搜索按钮到搜索面板
        JPanel searchPanel = new JPanel();
        searchPanel.add(new JLabel("搜索键:"));
        searchPanel.add(searchField);
        searchPanel.add(searchButton);

        // 设置文本框和按钮的字体大小和粗体
        Font inputFont = new Font(Font.SANS_SERIF, Font.BOLD, 15);
        keyTextField.setFont(inputFont);
        valueTextField.setFont(inputFont);
        addButton.setFont(inputFont);

        // 创建面板以容纳文本框和按钮
        JPanel inputPanel = new JPanel();
        inputPanel.add(new JLabel("键:"));
        inputPanel.add(keyTextField);
        inputPanel.add(new JLabel("值:"));
        inputPanel.add(valueTextField);
        inputPanel.add(addButton);
        inputPanel.add(exitButton);
        // 将清空按钮添加到界面
        inputPanel.add(clearButton);
        // 添加搜索面板到界面
        frame.add(searchPanel, BorderLayout.SOUTH);



        // 添加搜索按钮的点击事件监听器
        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String searchKey = searchField.getText().trim();

                if (searchKey.isEmpty()) {
                    // 如果搜索关键字为空，恢复显示所有键值对
                    loadPropertiesToTableModel();
                } else {
                    // 清空表格模型
                    tableModel.setRowCount(0);
                    // 遍历键值对，找到匹配的键值对并添加到表格模型中
                    for (Map.Entry<Object, Object> entry : properties.entrySet()) {
                        String key = (String) entry.getKey();
                        String value = (String) entry.getValue();
                        if (key.contains(searchKey) || value.contains(searchKey)) {
                            tableModel.addRow(new Object[]{key, value,"删除"});
                        }
                    }
                  /*  // 创建新的表格模型以显示搜索结果
                    DefaultTableModel searchResultModel = new DefaultTableModel();
                    searchResultModel.addColumn("键");
                    searchResultModel.addColumn("值");

                    // 遍历键值对，找到匹配的键值对并添加到搜索结果模型中
                    for (Map.Entry<Object, Object> entry : properties.entrySet()) {
                        String key = (String) entry.getKey();
                        String value = (String) entry.getValue();
                        if (key.contains(searchKey) || value.contains(searchKey)) {
                            searchResultModel.addRow(new Object[]{key, value,"删除"});
                        }
                    }

                    // 将搜索结果模型设置到表格
                    table.setModel(searchResultModel);*/
                }
            }
        });

        // 添加按钮的点击事件监听器
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String key = keyTextField.getText().trim();
                String value = valueTextField.getText().trim();

                if (key.isEmpty() || value.isEmpty()) {
                    JOptionPane.showMessageDialog(frame, "键和值不能为空。", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                if (properties.containsKey(key)) {
                    JOptionPane.showMessageDialog(frame, "键 '" + key + "' 已存在，跳过该项。", "警告", JOptionPane.WARNING_MESSAGE);
                } else if (properties.containsValue(value)) {
                    Set<String> keys = properties.stringPropertyNames();
                    boolean valueExistsWithDifferentKey = false;

                    for (String existingKey : keys) {
                        if (properties.getProperty(existingKey).equals(value) && !existingKey.equals(key)) {
                            valueExistsWithDifferentKey = true;
                            break;
                        }
                    }

                    if (valueExistsWithDifferentKey) {
                        int option = JOptionPane.showConfirmDialog(frame, "值 '" + value + "' 已存在，但键不同。是否录入已有的键值对？", "确认", JOptionPane.YES_NO_OPTION);
                        if (option == JOptionPane.YES_OPTION) {
                            properties.setProperty(key, value);
                            addedCount++;
                            JOptionPane.showMessageDialog(frame, "键 '" + key + "' ='" + value + "' 已录入成功。", "提示", JOptionPane.INFORMATION_MESSAGE);
                        } else {
                            JOptionPane.showMessageDialog(frame, "已跳过键 '" + key + "' 的录入。", "提示", JOptionPane.INFORMATION_MESSAGE);
                        }
                    } else {
                        JOptionPane.showMessageDialog(frame, "值 '" + value + "' 已存在，但键相同，跳过该项。", "警告", JOptionPane.WARNING_MESSAGE);
                    }
                } else {
                    properties.setProperty(key, value);
                    addedCount++;
                    JOptionPane.showMessageDialog(frame, "键 '" + key + "' ='" + value + "' 已录入成功。", "提示", JOptionPane.INFORMATION_MESSAGE);
                }

                // 清空文本框
                keyTextField.setText("");
                valueTextField.setText("");

                // 将属性加载到表格模型中并刷新表格
                loadPropertiesToTableModel();
            }
        });
// 添加按钮的点击事件监听器
        clearButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int option = JOptionPane.showConfirmDialog(frame, "确定要清空所有属性吗？", "确认", JOptionPane.YES_NO_OPTION);
                if (option == JOptionPane.YES_OPTION) {
                    // 清空properties对象
                    properties.clear();

                    // 保存清空后的properties对象到config.properties文件
                    try (OutputStream outputStream = new FileOutputStream("src/main/resources/config.properties")) {
                        properties.store(outputStream, null);
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }

                    // 清空表格模型
                    loadPropertiesToTableModel();

                    JOptionPane.showMessageDialog(frame, "所有属性已被清空。", "提示", JOptionPane.INFORMATION_MESSAGE);
                }
            }
        });


        // 添加退出按钮的点击事件监听器
        exitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        // 添加表格到滚动窗格
        JScrollPane tableScrollPane = new JScrollPane(table);

        // 将组件添加到界面
        frame.add(inputPanel, BorderLayout.NORTH);
        frame.add(tableScrollPane, BorderLayout.CENTER);

        // 显示初始的所有键值对
        frame.setVisible(true);
    }

    private void loadPropertiesToTableModel() {
        // 清空表格模型
        tableModel.setRowCount(0);

        for (Map.Entry<Object, Object> entry : properties.entrySet()) {
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            tableModel.addRow(new Object[]{key, value, "删除"});
        }
    }

    // 自定义按钮渲染器
    class ButtonRenderer extends JButton implements TableCellRenderer {
        public ButtonRenderer() {
            setOpaque(true);
        }

        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            if (isSelected) {
                setForeground(table.getSelectionForeground());
                setBackground(table.getSelectionBackground());
            } else {
                setForeground(table.getForeground());
                setBackground(UIManager.getColor("Button.background"));
            }
            setText((value == null) ? "" : value.toString());
            return this;
        }
    }

    // 自定义按钮编辑器
    class ButtonEditor extends DefaultCellEditor {
        protected JButton button;
        private String label;
        private boolean isPushed;

        public ButtonEditor(JCheckBox checkBox) {
            super(checkBox);
            button = new JButton();
            button.setOpaque(true);
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    fireEditingStopped();
                }
            });
        }

        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            if (isSelected) {
                button.setForeground(table.getSelectionForeground());
                button.setBackground(table.getSelectionBackground());
            } else {
                button.setForeground(table.getForeground());
                button.setBackground(table.getBackground());
            }
            label = (value == null) ? "" : value.toString();
            button.setText(label);
            isPushed = true;
            return button;
        }

        public Object getCellEditorValue() {
            if (isPushed) {
                // 点击按钮执行删除操作
                int option = JOptionPane.showConfirmDialog(frame, "确认删除该属性？", "确认", JOptionPane.YES_NO_OPTION);
                if (option == JOptionPane.YES_OPTION) {
                    int row = table.getSelectedRow();
                    if (row != -1) {
                        String keyToDelete = (String) table.getValueAt(row, 0);
                        properties.remove(keyToDelete);
                        loadPropertiesToTableModel();
                    }
                }
            }
            isPushed = false;
            return new String(label);
        }

        public boolean stopCellEditing() {
            isPushed = false;
            return super.stopCellEditing();
        }

        protected void fireEditingStopped() {
            super.fireEditingStopped();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new WriteToPropertiesSwingUpdatedWithDeleteButton01();
            }
        });
    }
}
